package com.ulk.systempermission.utils;

import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.provider.Settings;

import com.ulk.common_interface.Define;
import com.ulk.corelib.db.Packet;
import com.ulk.corelib.utils.log.LogUtils;
import com.ulk.systempermission_interface.SystemPermissionDefine;

import java.util.Calendar;

/**
 * the date time utils.
 *
 * @author xuxiaohong
 * @date 2016/5/18
 */
public class DateTimeUtils {
    public final String AUTO_TIME_GPS = "auto_time_gps";
    public enum TimeSource {GPS, NET, MANU, SMART};

    private Context mContext;
    private Thread mThread;
    private BroadcastReceiver mTimeChangedReceiver;

    private static DateTimeUtils mDateTimeUtils;

    private DateTimeUtils(Context context) {
        mContext = context;
    }

    public static DateTimeUtils newInstance(Context context) {
        if (null == mDateTimeUtils) {
            mDateTimeUtils = new DateTimeUtils(context);
        }
        return mDateTimeUtils;
    }

    public static DateTimeUtils getInstance() {
        return mDateTimeUtils;
    }

    public void registerSystemTimeChangedMonitor() {
        if (null != mContext) {
            if (null == mTimeChangedReceiver) {
                mTimeChangedReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        if (null != mThread) {
                            mThread.interrupt();
                        }
                    }
                };
                mContext.registerReceiver(mTimeChangedReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
            }
        }
    }

    public void unregisterSystemTimeChangedMonitor() {
        if (null != mContext) {
            if (null != mTimeChangedReceiver) {
                mContext.unregisterReceiver(mTimeChangedReceiver);
                mTimeChangedReceiver = null;
            }
        }
    }

    public void setTimeResource(TimeSource src, Packet packet) {
        if (null != mContext) {
            switch (src) {
                case GPS:
                    stopSmartSysncTime();
                    autoSyncGpsTime();
                    break;

                case NET:
                    stopSmartSysncTime();
                    autoSyncNetTime();
                    break;

                case MANU:
                    if (packet != null) {
                        stopSmartSysncTime();
                        manuSetTime();
                        setTime(
                                packet.getInt(Define.Time.YEAR),
                                packet.getInt(Define.Time.MONTH),
                                packet.getInt(Define.Time.DAY),
                                packet.getInt(Define.Time.HOURE),
                                packet.getInt(Define.Time.MUNITE),
                                packet.getInt(Define.Time.SECOND));
                    }
                    break;

                case SMART:
                    smartSyncTime();
                    break;
            }
        }
    }

    public void autoSyncGpsTime() {
        if (null != mContext) {
            LogUtils.d("TimeSetting", "Set to GPS");
            boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
            if (!gpsEnabled) {
                Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, true);
            }
            Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0);
            Settings.Global.putInt(mContext.getContentResolver(), AUTO_TIME_GPS, 1);
        }
    }

    public void autoSyncNetTime() {
        if (null != mContext) {
            LogUtils.d("TimeSetting", "Set to net");
            Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME, 1);
            Settings.Global.putInt(mContext.getContentResolver(), AUTO_TIME_GPS, 0);
        }
    }

    public void manuSetTime() {
        if (null != mContext) {
            LogUtils.d("TimeSetting", "Set to manu");
            Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0);
            Settings.Global.putInt(mContext.getContentResolver(), AUTO_TIME_GPS, 0);
        }
    }

    public void stopSmartSysncTime() {
        if (null != mThread) {
            mThread.interrupt();
        }
    }

    public void smartSyncTime() {
        if (null != mContext && null == mThread) {
            stopSmartSysncTime();
            mThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!Thread.currentThread().isInterrupted()) {
                        try {
                            LogUtils.d("TimeSetting", "Starting GPS time in 6000s");
                            //1分钟内GPS时间没有设置成功,则切换到网络同步模式
                            autoSyncGpsTime();
                            Thread.sleep(1000 * 60 * 1);

                            LogUtils.d("TimeSetting", "Starting net time in 10s");
                            //10s内没有获取到网络时间,则切换到Mcu的时间
                            autoSyncNetTime();
                            Thread.sleep(1000 * 10);
                            //3s内没有获取到mcu的时间, 则报告智能同步时间失败
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            LogUtils.d("TimeSetting", "Stop smart");
                        }
                        break;
                    }
                    mThread = null;
                }
            });
            mThread.start();
        }
    }

    public void setTimeFormat(Context context, String fromat) {
        if (null == context) {
            return;
        }

        if (Define.Time.FORMAT_12.equals(fromat)) {
            //Settings.System.putString(getContentResolver(), Settings.System.TIME_12_24, SystemPermissionDefine.Time.FORMAT_24);
            Settings.System.putString(context.getContentResolver(), Settings.System.TIME_12_24, "12");
        } else if (Define.Time.FORMAT_24.equals(fromat)) {
            Settings.System.putString(context.getContentResolver(), Settings.System.TIME_12_24, "24");
        }
    }

    private void setTime(int year, int month, int day, int hourOfDay, int minute, int second) {
        if (null != mContext) {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, year); // 年
            c.set(Calendar.MONTH, month); // 月
            c.set(Calendar.DAY_OF_MONTH, day); // 日
            c.set(Calendar.HOUR_OF_DAY, hourOfDay); // 时
            c.set(Calendar.MINUTE, minute); // 分
            c.set(Calendar.SECOND, second); // 秒
            AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
            am.setTime(c.getTimeInMillis());
        }
    }
}
